package com.winit.openapi.cwm.csi.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.winit.common.query.Page;
import com.winit.common.spi.context.CommandContext;
import com.winit.cwm.spi.common.command.WinitOrderNoCommand;
import com.winit.cwm.spi.csi.DeductionService;
import com.winit.cwm.spi.csi.InboundOrderService;
import com.winit.cwm.spi.csi.InboundPackageService;
import com.winit.cwm.spi.csi.command.AddInboundPackageCommand;
import com.winit.cwm.spi.csi.command.BatchPrintPackageLabelCommand;
import com.winit.cwm.spi.csi.command.CompleteInspectionCommand;
import com.winit.cwm.spi.csi.command.GetInboundOrderInfoCommand;
import com.winit.cwm.spi.csi.command.ImportInboundPackageCommand;
import com.winit.cwm.spi.csi.command.PageInboundMerchandiseCommand;
import com.winit.cwm.spi.csi.command.PageInboundMerchandisesCollectCommand;
import com.winit.cwm.spi.csi.command.PageInboundOrderCommand;
import com.winit.cwm.spi.csi.command.PageInboundPackageCommand;
import com.winit.cwm.spi.csi.command.PageInboundSingleitemCommand;
import com.winit.cwm.spi.csi.command.QueryMerchandiseForPrintCommand;
import com.winit.cwm.spi.csi.command.RemoveAddedPackagesCommand;
import com.winit.cwm.spi.csi.command.deduction.CancelDeductionCommand;
import com.winit.cwm.spi.csi.command.deduction.CompleteDeductionCommand;
import com.winit.cwm.spi.csi.command.deduction.DeductionNoCommand;
import com.winit.cwm.spi.csi.command.deduction.PageDeductionOrderCommand;
import com.winit.cwm.spi.csi.command.deduction.PageDeductionPackageCommand;
import com.winit.cwm.spi.csi.command.deduction.RemoveDeductionPackageCommand;
import com.winit.cwm.spi.csi.vo.InboundMerchandiseVo;
import com.winit.cwm.spi.csi.vo.InboundMerchandisesCollectVo;
import com.winit.cwm.spi.csi.vo.InboundOrderDetailForExportVo;
import com.winit.cwm.spi.csi.vo.InboundOrderVo;
import com.winit.cwm.spi.csi.vo.InboundPackageVo;
import com.winit.cwm.spi.csi.vo.InboundSingleitemVo;
import com.winit.cwm.spi.csi.vo.MerchandiseForPrintVo;
import com.winit.cwm.spi.csi.vo.deduction.DeductionOrderDetailVo;
import com.winit.cwm.spi.csi.vo.deduction.DeductionOrderVo;
import com.winit.cwm.spi.csi.vo.deduction.DeductionPackageVo;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.PDFBox4MergePDF;
import com.winit.ums.spi.UmsCustomerService;
import com.winit.ums.spi.commnad.customer.QueryCompanylCommand;
import com.winit.ums.spi.vo.CustomerInfoVO;

@Controller
@RequestMapping(value = "/csi/seller")
public class SellerOperationController extends BaseController {

    @Resource(name = "csiInboundOrderService")
    private InboundOrderService inboundOrderService;

    @Resource
    private InboundPackageService inspectPackageService;

    @Resource
    private DeductionService    deductionService;

    /**
     * ums客户信息
     */
    @Resource
    private UmsCustomerService  umsCustomerService;

    /**
     * 自验货订单列表
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/orders")
    public String orders(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取客户编码
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        String customerCode = (customer.getCode());
        if (StringUtils.isEmpty(customerCode)) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        PageInboundOrderCommand command = JSON.parseObject(requestMsg.getData().toString(),
            PageInboundOrderCommand.class);
        command.setCustomerCode(customerCode);
        command.setCtx(CommandContext.getContext());
        Page<InboundOrderVo> page = inboundOrderService.pageInboundOrders(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.getContent());
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    @RequestMapping(value = "/order")
    public String queryItemMtEntryDetail(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取客户编码
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        String customerCode = (customer.getCode());
        if (StringUtils.isEmpty(customerCode)) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        GetInboundOrderInfoCommand command = JSON.parseObject(requestMsg.getData().toString(),
            GetInboundOrderInfoCommand.class);
        command.setCustomerCode(customerCode);
        command.setCtx(CommandContext.getContext());
        InboundOrderVo vo = inboundOrderService.getInboundOrderInfo(command);
        responseMsg.setData(vo);
        return SUCCESS;
    }

    /**
     * 自验货订单下的包裹列表
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/order/pkgs")
    public String orderOfPackages(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取客户编码
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        String customerCode = (customer.getCode());
        if (StringUtils.isEmpty(customerCode)) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        PageInboundPackageCommand command = JSON.parseObject(requestMsg.getData().toString(),
            PageInboundPackageCommand.class);
        command.setCustomerCode(customerCode);
        command.setCtx(CommandContext.getContext());
        Page<InboundPackageVo> page = inboundOrderService.pageInboundPackages(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.content);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    /**
     * 自验货订单下的商品列表
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/order/merchs")
    public String orderOfMerchs(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取客户编码
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        String customerCode = (customer.getCode());
        if (StringUtils.isEmpty(customerCode)) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        PageInboundMerchandiseCommand command = JSON.parseObject(requestMsg.getData().toString(),
            PageInboundMerchandiseCommand.class);
        command.setCustomerCode(customerCode);
        command.setCtx(CommandContext.getContext());
        Page<InboundMerchandiseVo> page = inboundOrderService.pageInboundMerchandises(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.content);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    /**
     * 自验货订单下的商品汇总列表
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/order/merchsCollect")
    public String orderOfMerchsCollect(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取客户编码
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        String customerCode = (customer.getCode());
        if (StringUtils.isEmpty(customerCode)) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        PageInboundMerchandisesCollectCommand command = JSON.parseObject(requestMsg.getData().toString(),
            PageInboundMerchandisesCollectCommand.class);
        command.setCustomerCode(customerCode);
        command.setCtx(CommandContext.getContext());
        Page<InboundMerchandisesCollectVo> page = inboundOrderService.pageInboundMerchandisesCollect(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.content);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    /**
     * 自验货订单下的单品列表
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/order/sis")
    public String orderOfSis(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取客户编码
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        String customerCode = (customer.getCode());
        if (StringUtils.isEmpty(customerCode)) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        PageInboundSingleitemCommand command = JSON.parseObject(requestMsg.getData().toString(),
            PageInboundSingleitemCommand.class);
        command.setCustomerCode(customerCode);
        command.setCtx(CommandContext.getContext());
        Page<InboundSingleitemVo> page = inboundOrderService.pageInboundSingleitems(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.content);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    /**
     * 完成自验货
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/completeInspection")
    public String completeInspection(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        CompleteInspectionCommand command = JSON.parseObject(requestMsg.getData().toString(), CompleteInspectionCommand.class);
        command.setCustomerCode(this.getContextCustomer().getCode());
        inboundOrderService.completeInspection(command);
        return SUCCESS;
    }

    /**
     * 网页上查询扣货单详情
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryDeductionOrderDetail")
    public String queryDeductionOrderDetail(@ModelAttribute RequestMsg requestMsg,
                                            @ModelAttribute ResponseMsg responseMsg) {
        DeductionNoCommand command = JSON.parseObject(requestMsg.getData().toString(), DeductionNoCommand.class);
        DeductionOrderDetailVo deductionOrderDetailVo = deductionService.queryDeductionOrder(command);
        responseMsg.setData(deductionOrderDetailVo);
        return SUCCESS;
    }

    /**
     * 分页查询扣货订单列表
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/deductionOrders")
    public String deductionOrders(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        PageDeductionOrderCommand command = JSON.parseObject(requestMsg.getData().toString(),
            PageDeductionOrderCommand.class);
        command.setCustomerCode(this.getContextCustomer().getCode());
        Page<DeductionOrderVo> page = deductionService.pageDeductionOrder(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.getContent());
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    /**
     * 分页查询扣货订单下扣货包裹列表
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/pageDeductionPackage")
    public String pageDeductionPackage(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        PageDeductionPackageCommand command = JSON.parseObject(requestMsg.getData().toString(),
            PageDeductionPackageCommand.class);
        Page<DeductionPackageVo> page = deductionService.pageDeductionPackage(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.content);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    /**
     * 完成 扣货
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/completeDeduction")
    public String completeDeduction(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        CompleteDeductionCommand command = JSON.parseObject(requestMsg.getData().toString(),
            CompleteDeductionCommand.class);

        CustomerInfoVO customer = this.getContextCustomer();
        command.setCustomerCode(customer.getCode());
        deductionService.completeDeduction(command);

        return SUCCESS;
    }

    /**
     * 取消扣货
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/cancelDeduction")
    public String cancelDeduction(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        CancelDeductionCommand command = JSON.parseObject(requestMsg.getData().toString(), CancelDeductionCommand.class);
        CustomerInfoVO customer = getContextCustomer();
        command.setCustomerCode(customer.getCode());
        CommandContext ctx = CommandContext.getContext();
        ctx.setUsername(customer.getUsername());
        command.setCtx(ctx);
        deductionService.cancelDeduction(command);
        return SUCCESS;
    }

    /**
     * 删除扣货包裹
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/removeDeductionPackage")
    public String removeDeductionPackage(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        RemoveDeductionPackageCommand command = JSON.parseObject(requestMsg.getData().toString(),
            RemoveDeductionPackageCommand.class);
        CustomerInfoVO customer = getContextCustomer();
        command.setCustomerCode(customer.getCode());
        CommandContext ctx = CommandContext.getContext();
        ctx.setUsername(customer.getUsername());
        command.setCtx(ctx);

        deductionService.removeDeductionPackage(command);
        return SUCCESS;
    }

    /**
     * 分页查询商品列表
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/pageMerchandise")
    public String pageMerchandise(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        PageInboundMerchandiseCommand command = JSON.parseObject(requestMsg.getData().toString(), PageInboundMerchandiseCommand.class);
        Page<InboundMerchandiseVo> page = inboundOrderService.pageInboundMerchandises(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.getContent());
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    /**
     * 分页查询单品列表
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/pageSingleItem")
    public String pageSingleItem(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        PageInboundSingleitemCommand command = JSON.parseObject(requestMsg.getData().toString(), PageInboundSingleitemCommand.class);
        Page<InboundSingleitemVo> page = inboundOrderService.pageInboundSingleitems(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.getContent());
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    /**
     * 导出入库单验货详情
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/exportOrderDetail")
    public String exportOrderDetail(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        WinitOrderNoCommand command = JSON.parseObject(requestMsg.getData().toString(), WinitOrderNoCommand.class);

        InboundOrderDetailForExportVo vo = inboundOrderService.queryInboundOrderDetailForExport(command);
        responseMsg.setData(vo);

        return SUCCESS;
    }

    /**
     * 新增包裹
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/addInboundPackage")
    public String addInboundPackage(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        AddInboundPackageCommand command = JSON.parseObject(requestMsg.getData().toString(), AddInboundPackageCommand.class);
        String customerCode = this.getContextCustomer().getCode();
        command.setCustomerCode(customerCode);
        inspectPackageService.addInboundPackage(command);
        return SUCCESS;
    }

    @RequestMapping(value = "/importInboundPackages")
    public String importInboundPackages(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        ImportInboundPackageCommand command = JSON.parseObject(requestMsg.getData().toString(), ImportInboundPackageCommand.class);
        command.setCustomerCode(this.getContextCustomer().getCode());
        inspectPackageService.importInboundPackage(command);

        return SUCCESS;
    }

        /**
         * 编辑新增包裹
         * @param requestMsg
         * @param responseMsg
         * @return
         */
    @RequestMapping(value = "/editAddedPackage")
    public String editAddedPackage(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        AddInboundPackageCommand command = JSON.parseObject(requestMsg.getData().toString(), AddInboundPackageCommand.class);
        command.setCustomerCode(this.getContextCustomer().getCode());
        inspectPackageService.updateAddedPackage(command);
        return SUCCESS;
    }

    /**
     * 删除新增包裹
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/removeAddedPackages")
    public String removeAddedPackages (@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        RemoveAddedPackagesCommand command = JSON.parseObject(requestMsg.getData().toString(), RemoveAddedPackagesCommand.class);
        command.setCustomerCode(this.getContextCustomer().getCode());
        inspectPackageService.removeAddedPackages(command);
        return SUCCESS;
    }


    @RequestMapping(value = "/printPackageLabelBatch")
    public String printPackageLabelBatch (@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        BatchPrintPackageLabelCommand command = JSON.parseObject(requestMsg.getData().toString(), BatchPrintPackageLabelCommand.class);
        List<String> bytes = inspectPackageService.printPackageLabelBatch(command);

        PDFBox4MergePDF tool = new PDFBox4MergePDF();
        ByteArrayOutputStream out=new ByteArrayOutputStream();

        try {
            List<byte []> byteList= tool.decryptBASE64(bytes);
            tool.merge(byteList, out);
        } catch (IOException e) {
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }
        Map<String, Object> dataMap=new HashMap<String, Object>();
        String mergeByte= tool.base64Encode(out.toByteArray());

        if (mergeByte!=null && mergeByte.length()>0) {
            dataMap.put("files", mergeByte);
        }
        responseMsg.setData(dataMap);

        return SUCCESS;
    }

    @RequestMapping(value = "/queryMerchandiseForPrint")
    public String queryMerchandiseForPrint(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        QueryMerchandiseForPrintCommand command = JSON.parseObject(requestMsg.getData().toString(), QueryMerchandiseForPrintCommand.class);
        command.setCustomerCode(this.getContextCustomer().getCode());
        List<MerchandiseForPrintVo> vos = inspectPackageService.queryMerchandiseForPrint(command);
        responseMsg.setData(vos);
        return SUCCESS;
    }


    private CustomerInfoVO getContextCustomer() {
        // 获取客户编码
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND);
        }
        return customer;
    }
}
